import { Service } from "../../services/service";
import { config } from "../config";
import { MemberService } from "./memberService";

var ua = navigator.userAgent.toLowerCase();
export let isWeixin = (ua.match(/MicroMessenger/i) as any) == 'micromessenger';

export function createWeixinClient(weixin: WeiXinService) {
    return new Promise<jweixin>((resolve, reject) => {
        var config = {
            debug: false,
            nonceStr: 'mystore',
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'getLocation', 'chooseImage', 'getLocalImgData']
        };

        requirejs(['jweixin'], function (wx: jweixin) {
            var url = encodeURIComponent(location.href.split('#')[0]);
            weixin.jsSignature(config.nonceStr, url).then(function (obj) {
                config = Object.assign(config, obj);
                wx.config(config);
                wx.ready(function () {
                    resolve(wx);
                });
                wx.error((res) => {
                    let error = new Error();
                    error.message = res.errMsg;
                    reject(error);
                });
            });
        }, function (err) {
            reject(err);
        })
    })
}

if (isWeixin) {
    // let iframe = document.createElement("iframe");
    // iframe.style.display = "none";
    // iframe.src = "http://web.alinq.cn/weixin/auth/code";
    // document.body.appendChild(iframe);
    // debugger
    // let callbackURL = encodeURIComponent(`http://web.alinq.cn/weixin/auth/callback`);
    // let scope: "snsapi_base" | "snsapi_userinfo" = "snsapi_base";
    // let appId = "wxf1c24c60e3ac13b7";
    // let targetURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${callbackURL}&response_type=code&scope=${scope}#wechat_redirect`

    // fetch("http://web.alinq.cn/weixin/auth/code").then(r => {

    //     debugger;
    // })
}

export class WeiXinService extends Service {
    private config: { appId: string; partnerId: string; };
    constructor() {
        super();
    }
    private url(path) {
        return `${config.weixinUrl}${path}`;
    }
    openid(value?: string) {
        if (value === undefined)
            return "oYHEKuMV8Kt0QLBIMjmZfxoWwsjU";//localStorage.getItem('openid');

        if (value == null) {
            localStorage.removeItem("openid");
        }

        localStorage.setItem("openid", value);
    }
    jsSignature(noncestr, url) {
        var data = { noncestr: noncestr, url: url };
        let u = this.url('WeiXin/GetJsSignature');
        return this.getByJson(u, data);
    }
    // async login(code: string): Promise<LoginResult> {
    //     let url = this.url('Member/Login');
    //     let result = await this.postByJson<LoginResult | { UserId: string }>(url, { code });
    //     let userId = (result as { UserId: string }).UserId;
    //     if (userId) {
    //         let memberService = this.createService(MemberService);
    //         let url = `UserMember/User/RegisterById`;
    //         result = await this.postByJson<LoginResult>(url, { userId });
    //     }

    //     // tokens.userToken.value = (result as LoginResult).token;
    //     return result as LoginResult;
    // }

    getPrepayId(openId: string, order: Order) {
        type Result = { prepay_id: string };
        let url = "http://web.alinq.cn/weixin/pay/prepayid";
        return this.postByJson<Result>(url, { openId, order: order });
    }

    async getSign(args: { [key: string]: string }) {
        let url = "http://web.alinq.cn/weixin/paySign";
        let r = await this.get<string>(url, args);
        return r;
    }

    /** 获取微信配置 */
    async getConfig() {
        if (!this.config) {
            let url = "http://web.alinq.cn/weixin/config";
            type Result = { appId: string, partnerId: string };
            this.config = await this.get<Result>(url);
        }
        return this.config;;
    }

    async getPayArgs(openid: string, order: Order) {
        let r = await this.getPrepayId(openid, order);
        debugger
        let config = await this.getConfig();
        var args = {
            appId: config.appId,
            nonceStr: this.getNonceStr(),
            'package': "prepay_id=" + r.prepay_id,
            timeStamp: this.getTimeStamp(),
            signType: 'MD5',
        }

        let paySign: string = await this.getSign(args);
        args["paySign"] = paySign;

        return args;
    }

    private getNonceStr() {
        var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var maxPos = $chars.length;
        var noceStr = "";
        for (let i = 0; i < 32; i++) {
            noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return noceStr;
    }


    private getTimeStamp() {
        var timestamp = new Date().getTime();
        var timestampstring = timestamp.toString();//一定要转换字符串
        return timestampstring;
    }


    weixinPay(prepayId): Promise<string> {
        /// <returns type="jQuery.Deferred"/>
        function getTimeStamp() {
            var timestamp = new Date().getTime();
            var timestampstring = timestamp.toString();//一定要转换字符串
            return timestampstring;
        }

        function getNonceStr() {
            var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var maxPos = $chars.length;
            var noceStr = "";
            for (var i = 0; i < 32; i++) {
                noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return noceStr;
        }


        return new Promise((resolve, reject) => {

            var nonceStr = getNonceStr();
            var timeStamp = getTimeStamp();
            var pack = "prepay_id=" + prepayId;
            var paySignatureDeferred = this.paySignature(nonceStr, pack, timeStamp);

            paySignatureDeferred.then(function (data) {
                window['WeixinJSBridge'].invoke('getBrandWCPayRequest', {
                    "appId": data.appId,                     //公众号名称，由商户传入
                    "nonceStr": nonceStr,          //随机串
                    "package": pack,//扩展包
                    "timeStamp": timeStamp, //时间戳
                    "signType": 'MD5', //微信签名方式
                    "paySign": data.paySign //微信签名
                }, function (res) {

                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        resolve();
                    }
                    else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                        reject();
                    }
                    else {
                        alert(res.err_msg);
                        let err: Error = { name: "", message: res.err_msg };
                        reject(err);
                    }
                });
            })
        })
    }

    private paySignature(nonceStr, pack, timeStamp) {
        /// <returns type="jQuery.Deferred"/>
        var data = { nonceStr: nonceStr, 'package': pack, timeStamp: timeStamp };
        return this.postByJson<any>('WeiXin/GetPaySignature', data);
    }

}


